//
//  KKNetworkRequest.m
//  XiaoShi
//
//  Created by leo on 2017/6/15.
//  Copyright © 2017年 liaozhenming. All rights reserved.
//

#import "KKNetworkRequest.h"

@implementation KKNetworkRequest

+ (KKNetworkRequest *)requestWithHost:(NSString*)host interfaceName:(NSString*)interfaceName parmeters:(NSDictionary*)parmeters {
    return [self requestWithHost: host interfaceName: interfaceName parmeters: parmeters methodType: KKNetworkRequestMethodType_Get];
}
+ (KKNetworkRequest *)requestWithHost:(NSString*)host interfaceName:(NSString*)interfaceName parmeters:(NSDictionary*)parmeters methodType:(KKNetworkRequestMethodType)methodType {
    return [[KKNetworkRequest alloc] initWithHost: host interfaceName: interfaceName parmeters: parmeters methodType: methodType];
}

- (instancetype)initWithHost:(NSString*)host interfaceName:(NSString*)interfaceName parmeters:(NSDictionary*)parmeters methodType:(KKNetworkRequestMethodType)methodType{
    self = [super init];
    if (self) {
        self.requestHost = host;
        self.requestInterfaceName = interfaceName;
        self.methodType = methodType;
        self.requestParmeters = parmeters;
    }
    return self;
}

- (NSString*)requestURL {
    NSMutableString *string = [NSMutableString string];
    if (self.requestHost) {
        [string appendString: self.requestHost];
    }
    if (self.requestInterfaceName) {
        [string appendString: self.requestInterfaceName];
    }
    return string;
}

- (NSData*)requestPostData {
    if (self.requestParmeters) {
        
//        NSString *parmeterString = [self requestParmeterString];
//        return [parmeterString dataUsingEncoding: NSUTF8StringEncoding];
        return [NSJSONSerialization dataWithJSONObject: self.requestParmeters options:NSJSONWritingPrettyPrinted error: nil];
    }
    return nil;
}

- (NSString*)requestParmeterString {
    NSMutableString *string = [NSMutableString string];
    if (self.requestParmeters.count > 0) {
        for (NSString *key in self.requestParmeters.allKeys) {
            if (string.length > 0) {
                [string appendFormat:@"&"];
            }
            [string appendFormat: @"%@=%@",key, self.requestParmeters[key]];
        }
    }
    return string;
}

@end
